package com.leftheart.config;


import com.leftheart.entity.Books;
import com.leftheart.entity.User;
import com.leftheart.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    //    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

//        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("[user:add]");
//        info.addStringPermission("[user:update]");
////        拿到当前登录对象
//        Subject subject = SecurityUtils.getSubject();
////      拿到user对象
//        User currentUser = (User) subject.getPrincipal();
//        info.addStringPermission(currentUser.getPerms());


//        return info
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
//        //获取当前用户
//        Subject subject = SecurityUtils.getSubject();
//        //封装用户的登录数据
//        new UsernamePasswordToken();
//        String name="root";
//        String password="123456";

//      token携带用户信息
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        String username = userToken.getUsername();

        //调用service方法判断该用户名是否存在
        User user = userService.queryUserByName(username);

        if (user==null){
            //抛出用户名不存在的错误
            throw new UnknownAccountException("用户名不存在");
        }
        //根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo
        //通常需要以下四个参数
        //1). principal: 认证的实体信息. 可以是 username, 也可以是数据表对应的用户的实体类对象.
        Object principal = user;
        //2). credentials: 密码.即从数据库中获取的密码
        Object credentials = user.getUserPwd();
        //3). realmName: 当前 realm 对象的 name. 调用父类的 getName() 方法即可
        String realmName = getName();
        //4). credentialsSalt: 盐值,这里我使用的是用户名
        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUserName());
        return new SimpleAuthenticationInfo(principal,credentials,credentialsSalt,realmName);

    }


}
